<?php

namespace app\manystore\controller;

use app\common\controller\ManystoreBase;
use fast\Date;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\PDOException;
use fast\Idcard;
use think\exception\ValidateException;
use Exception;
/**
 * 发团线路
 *
 * @icon fa fa-circle-o
 */
class GoodsCustomer extends ManystoreBase
{

    /**
     * GoodsCustomer模型对象
     * @var \app\manystore\model\GoodsCustomer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\GoodsCustomer;
        $this->view->assign("genderList", $this->model->getGenderList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */





    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','branchofficeoffice','manystoreshop','goods','manystore'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['join_num','level']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }
                //加上分公司
                if($this->officeIdAutoCondition && OFFICE_ID){
                    $params['office_id'] = OFFICE_ID;
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                //    $result = $this->model->allowField(true)->save($params);
                    $this->addCustomer($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error("该客户已经报名");
                    //$msg = "导入失败，第{$line}记录已经存在";
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success();
//                if ($result !== false) {
//                    $this->success();
//                } else {
//                    $this->error(__('No rows were inserted'));
//                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if($this->shopIdAutoCondition){
            $this->model->where(array('shop_id'=>SHOP_ID));
        }
        $row = $this->model->where(array('id'=>$ids))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //线路选择错误 或者会员添加错误
                    if($row['goods_id']!=$params['goods_id'] || $row['idcard']!=$params['idcard']){
                        //删除线路客户
                        $goods = \app\manystore\model\Goods::get($row['goods_id']);
                        $goods->setDec('person_real');
                        //尝试删除对应的会员信息
                        $user = \app\common\model\User::get($row['user_id']);
                        $user->setDec('join_num');
                        if($user['join_num']==0){
                            $user->delete();
                        }
                        //删除客户
                        $row->delete();
                        $this->addCustomer($params);
                        $result =true;
                    }else{
                        $result = $row->allowField(true)->save($params);
                    }




                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function batch_import(){

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->import();



    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    protected function import()
    {
        $params = $this->request->post('row/a');


        $file = $params['file'];
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }



        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [
                'goods_no',
                'username',
                'idcard',
                'nation',
                'mobile',
                'price',
                'remark',
            ];


            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $temp = array_combine($fields, $values);
                $insert[] = $temp;

            }

        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        Db::startTrans();
        try {
            foreach ($insert as $key =>$item){
                $line = $key+2;
                $this->addCustomer($item);
            } //foreach end
            Db::commit();
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
            //    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                $msg = "导入失败，第{$line}记录已经存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error("第{$line}行".$e->getMessage());
        }

        $this->success();
    }




    private function addCustomer($data){
        if(!isset($data['username'])){
            exception('客户姓名必须输入');
        }
        if(!isset($data['idcard'])){
            exception('客户身份号码必须输入');
        }
        //验证身份证并且计算客户年龄
        $id_card = new Idcard();
        !$id_card->isChinaIDCard($data['idcard'])&&  exception("身份证号码错误");
        $goods =null;
        //客户关联线路
        if(isset($data['goods_id'])){
            $goods = \app\manystore\model\Goods::get($data['goods_id']);
        }elseif(isset($data['goods_no'])){
            $goods = \app\manystore\model\Goods::get(['goods_no'=>trim($data['goods_no'])]);
        }

        !$goods && exception("线路输入值错误");
        $goods['status'] == 'hidden' && exception('线路已经锁单，不能报名');
        $goods_category =  \app\manystore\model\GoodsCategory::get($goods['category_id']);
        $customer = [
            'username'=>$data['username'],
            'idcard'=>$data['idcard'],
            'age' =>(int)\date('Y')-(int)mb_substr($id_card->birthday,0,4),
            'goods_id'=>$goods['id'],
            'office_id'=>OFFICE_ID,
            'shop_id'=>SHOP_ID,
            'store_id'=>STORE_ID,
            'updatetime'=>time(),
            'createtime'=>time(),


        ];

        //判单会员是否已经存在
        $user = \app\common\model\User::where('idcard',$data['idcard'])->find();
        if(!$user){
            $user_new = [
                'username'=>$customer['username'],
                'idcard'=>$customer['idcard'],
                'age' =>$customer['age'],
                'join_num'=>$goods_category['status'] ? 1:0,
                'updatetime'=>time(),
                'createtime'=>time(),
            ];
            $user_id = \app\common\model\User::insertGetId($user_new);
        }else{
            $user['status'] == 'hidden' && exception('客户已经被拉黑，不能报名');
            //只有要上会的种类，报名才计上会
            $goods_category['status']&& $user->setInc('join_num');
        }
        $customer['user_id'] = $user?$user['id']:$user_id;
        //客户报名是否给会员增加上会次数
        $customer['user_join_num_add'] = $goods_category['status'];

        \app\manystore\model\GoodsCustomer::insert($customer);
        $goods->setInc('person_real');



    }



}
